package com.tywj.buscustomerapp.view.fragment;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.PoiItem;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BusTravelBean;
import com.tywj.buscustomerapp.model.bean.CityBean;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.myadapter.CommonRcvAdapter;
import com.tywj.buscustomerapp.utils.myadapter.RcvAdapterWrapper;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.activity.ChooseLocationActivity;
import com.tywj.buscustomerapp.view.activity.SearchActivity;
import com.tywj.buscustomerapp.view.item.BusLineItem;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.ToastJoe;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class newTravelFragment extends BaseFragment  implements Response.Listener,Response.ErrorListener{
    private String Tag = "newTravelFragment";
    private static newTravelFragment fragment = new newTravelFragment();
    private ImageView exchange;
    private TextView startText;
    private TextView endText;
    private ImageView search;
    private RelativeLayout error;
    private RecyclerView recyclerView;
    private TextView error_btn;
    private RelativeLayout error_null;
    private TextView error_null_btn;
    private SmartRefreshLayout srl;
    private String end;
    private String start;
    private List<BusTravelBean.DataBean.ResultListBean> lines = new ArrayList<>();
    private CommonRcvAdapter<BusTravelBean.DataBean.ResultListBean> adapter;
    private int page = 1;
    private int size = 20;
    private RcvAdapterWrapper raw;
    private View header;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;


    public static newTravelFragment getInstance() {
        return fragment;
    }

    @Override
    protected void ititClick() {
        exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (start!=null && !start.equals("上车地点") && !start.equals("") && !start.equals("下车地点")
                        && end!=null && !end.equals("上车地点") && !end.equals("下车地点") && !end.equals("")) {
                    exchangeText();
                    String[] cash = SPUtils.getStartAndEnd(getContext().getApplicationContext());
                    double[] cashL = SPUtils.getStartAndEndLatLng(getContext().getApplicationContext());
                    SPUtils.rememberStart(getContext().getApplicationContext(),cash[1],cashL[2]+"",cashL[3]+"");
                    SPUtils.rememberEnd(getContext().getApplicationContext(),cash[0],cashL[0]+"",cashL[1]+"");
                }
            }
        });
        startText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
                intent.putExtra("type",0);
                startActivityForResult(intent,0);
            }
        });

        endText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double[] addressss= SPUtils.getStartAndEndLatLng(getContext().getApplicationContext());
                boolean isok = true;
                if (addressss.length==4){
                    for (int i = 0; i < 4; i++) {
                        if (addressss[i]==0){
                            isok = false;
                        }
                    }
                    if (isok){
                        Intent intent = new Intent(getContext(), SearchActivity.class);
                        intent.putExtra("start&end",SPUtils.getStartAndEndLatLng(getContext().getApplicationContext()));
                        startActivity(intent);
                    }else{
                        ToastJoe.getmToastJoe().ToastLongShow(getContext(),null,"请选择上车点或下车点");
                    }
                }else {
                    ToastJoe.getmToastJoe().ToastLongShow(getContext(),null,"请选择上车点或下车点");
                }
            }
        });
        srl.setEnableAutoLoadmore(true);
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

            }
        });
        srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                loadData(false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(true);
            }
        });
        error_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(true);
//                srl.autoRefresh();
                error.setVisibility(View.GONE);
            }
        });

        error_null_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(true);
//                srl.autoRefresh();
                error_null.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_travel;
    }

    public void loadData(boolean isClean) {
        if (isClean){
            page=1;
            lines.clear();
            lines.clear();
            showLoading();
        }
        CityBean cityBean = SPUtils.getCity(getActivity().getApplicationContext());
        String cityId = "001";
        if (cityBean !=null && cityBean.getCityId()!=null && !cityBean.getCityId().equals("") ){
            cityId = cityBean.getCityId();
        }
        RequestQueue requestQueue = Volley.newRequestQueue(this.getContext());
        String url = Config.APIURL + "line/listPage";
        JSONObject object = new JSONObject();
        try {
            object.put("page",page);
            object.put("size",size);
            object.put("cs",cityId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object,this , this);
        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(jsonObjectRequest);
    }

    @Override
    protected void lazyLoad() {
        recyclerView = findViewById(R.id.travel_recycler);
        srl = findViewById(R.id.class_refresh);
        error = findViewById(R.id.error);
        error_btn = findViewById(R.id.error_btn);
        error_null = findViewById(R.id.error_null);
        error_null_btn = findViewById(R.id.error_null_btn);
        start = SPUtils.getStartAndEnd(getActivity().getApplicationContext())[0];
        end = SPUtils.getStartAndEnd(getActivity().getApplicationContext())[1];
        adapter  = new CommonRcvAdapter<BusTravelBean.DataBean.ResultListBean>(lines) {
            @NonNull
            @Override
            public AdapterItem createItem(Object type) {
                return new BusLineItem();
            }
        };
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        header = View.inflate(getActivity(),R.layout.search_head_layout,null);
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
        header.setLayoutParams(layoutParams);
        exchange = header.findViewById(R.id.travel_exchange);
        search = header.findViewById(R.id.travel_search);
        startText = header.findViewById(R.id.start_text);
        endText = header.findViewById(R.id.end_text);
        if (start==null || start.equals("") || start.equals("上车地点")) {
            start = "上车地点";
            startText.setText("上车地点");
        }else
            startText.setText(start);
        if (end==null || end.equals("") || end.equals("下车地点")) {
            end = "下车地点";
            endText.setText("下车地点");
        }else
            endText.setText(end);
        raw = new RcvAdapterWrapper(adapter,layoutManager);
        raw.setHeaderView(header);
        recyclerView.setAdapter(raw);
        recyclerView.setLayoutManager(layoutManager);
        loadData(true);


    }

    public void startGetLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationCacheEnable(false);//关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (!aMapLocation.getPoiName().equals("")) {
                start = aMapLocation.getPoiName();
                startText.setText(start);
                SPUtils.rememberStart(getActivity().getApplicationContext(), start, aMapLocation.getLatitude() + "",
                        aMapLocation.getLongitude() + "");
            }
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1001) {
            PoiItem poi = data.getParcelableExtra("poi");
            switch (requestCode){
                case 0:
                    if (poi!=null){
                        start = poi.getTitle();
                        startText.setText(start);
                        SPUtils.rememberStart(getActivity().getApplicationContext(),start,poi.getLatLonPoint().getLatitude()+"",
                                poi.getLatLonPoint().getLongitude()+"");
                    }
                    break;
                case 1:
                    if (poi!=null){
                        end = poi.getTitle();
                        endText.setText(end);
                        SPUtils.rememberEnd(getActivity().getApplicationContext(),end,poi.getLatLonPoint().getLatitude()+"",
                                poi.getLatLonPoint().getLongitude()+"");
                    }
                    break;
            }
        }else if (resultCode==1002){
            loadData(true);
        }

    }

    private LoadingDialog waitDialog;
    public void showLoading() {
        try {
            if (waitDialog==null)
                waitDialog = new LoadingDialog(getContext());
            if (!waitDialog.isShowing())
                waitDialog.show();
        }catch (WindowManager.BadTokenException e){
            waitDialog=null;
        }

    }

    public void closeLoading() {
        try {
            if (waitDialog != null && waitDialog.isShowing())
                waitDialog.dismiss();
        }catch (IllegalArgumentException e) {

        }
    }



    @Override
    public void onResponse(Object response) {
        closeLoading();
        BusTravelBean data = new Gson().fromJson(String.valueOf(response),BusTravelBean.class);
        Log.i(Tag,data.toString());
        if (data.getReCode().equals("201")){
            lines.addAll(data.getData().getResultList());

            if (srl!=null && srl.isRefreshing()){
                srl.finishRefresh();
            }
            if (srl!=null && srl.isLoading()){
                srl.finishLoadmore();
            }
            adapter.setData(lines);
            adapter.notifyDataSetChanged();
        }else{
            ToastJoe.getmToastJoe().ToastLongShow(this.getContext(),null,data.getCodeTxt());
            error_null.setVisibility(View.VISIBLE);
            if (page>1)
                page--;
        }
        startGetLocation();
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        closeLoading();
        if (page>1)
            page--;
        ToastJoe.getmToastJoe().ToastLongShow(this.getContext(),null,"网络错误请重试");
        this.error.setVisibility(View.VISIBLE);
    }


    private void exchangeText(){
        int[] position = new int[2];
        startText.getLocationOnScreen(position);
        int[] position1 = new int[2];
        endText.getLocationOnScreen(position1);
        Animation translateAnimation=new TranslateAnimation(0,0,0,position1[1]-position[1]);
        translateAnimation.setDuration(500);
        startText.startAnimation(translateAnimation);
        Animation translateAnimation1=new TranslateAnimation(0,0,0,position[1]-position1[1]);
        translateAnimation1.setDuration(500);
        endText.startAnimation(translateAnimation1);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startText.clearAnimation();
                endText.clearAnimation();
                String cash = end;
                end = start;
                start = cash;
                startText.setText(start);
                endText.setText(end);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

}
